import { AfterViewInit, Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { listAnimation } from '../../../../animations/list.animation';
import { BaseUI } from '../../../../common/base';
import { ConfigModule } from '../../../../config.module';
import { UserService } from '../../user/service/user.service';
import { AppRoutingModule } from '../../../../app-routing.module';

@Component({
    selector: 'app-assign-role',
    templateUrl: './index.component.html',
    styleUrls: ['./index.component.scss'],
    animations: [listAnimation]
})
export class AssignRoleComponent extends BaseUI implements OnInit, AfterViewInit, OnDestroy {
    onDestroy$: Subject<any> = new Subject<any>();
    userId:string;
    user: any = {};
    roles: any[] = [];
    constructor(
        public _config: ConfigModule,
        private _router: Router,
        private _injector: Injector,
        public userService: UserService,
        public appRoutingModule: AppRoutingModule
    ) {
        super(_injector);
        const urlParts = this._router.url.split('/');
        this.userId = urlParts[urlParts.length - 1];
        this.authUser();
    }

    ngOnInit() {
        // this._config.scrollValue.x = super.getTableWidth();
    }

    ngAfterViewInit() {}

    ngOnDestroy() {
        this.onDestroy$.complete();
    }


    authUser(){
        this.userService.getAuthUser(this.userId).subscribe(res => {
            if (res.success) {
                this.user = res.user;
                this.roles = res.roles;
                this.roles.forEach(item=>{
                    if (item.flag){
                        this.updateCheckedSet(item.roleId, true)
                    }
                })
            }
        })
    }

    @ViewChild('rowSelectionTable') rowSelectionTable: ElementRef;
    checked = false;
    loading = false;
    indeterminate = false;
    setOfCheckedId = new Set<number>();

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
    this.refreshStatus();
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
  }

  onAllChecked(checked: boolean): void {
    this.roles.forEach(item => this.updateCheckedSet(item.roleId, checked));
  }

  refreshStatus() {
      if (this.setOfCheckedId.size == 0){
          this.indeterminate = false;
          this.checked = false;
      }
      else if (this.setOfCheckedId.size == this.roles.length){
          this.indeterminate = false;
          this.checked = true;
      }
      else if (this.setOfCheckedId.size > 0){
          this.indeterminate = true;
      }
  }

    sendRequest(): void {
      this.loading = true;
        this.userService.authUser(this.userId,Array.from(this.setOfCheckedId).join(',')).subscribe(res => {
            if (res.success){
                this.router.navigate([this.appRoutingModule.menusMap.get('User')]).finally();
            }
        }).add(() => (this.loading = false));
  }
}
